<?php

namespace app\user\admin;

use app\system\admin\Admin;
use app\user\model\User as UserModel;
use app\user\model\UserGroup as GroupModel;
use app\messages\model\Messages;
use app\user\model\UserGroup;
use app\videos\model\Subscribe;
use one\Http;

/**
 * 会员控制器
 * @package app\user\admin
 */
class Index extends Admin
{
    protected $oneModel = 'User'; //模型名称[通用添加、修改专用]
    protected $oneAddScene = 'adminCreate'; //添加数据验证场景名
    protected $oneEditScene = ''; //更新数据验证场景名

    /**
     * 会员管理
     *
     * @return void
     * @author 617 <email：723875993@qq.com>
     */
    public function index()
    {
        if ($this->request->isAjax()) {

            $where      = [];
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 15);
            $keyword    = $this->request->param('keyword/s');
            $groupId    = $this->request->param('level_id/d');

            if ($keyword) {
                $page = 1;
                if (is_email($keyword)) { // 邮箱
                    $where[] = ['email', 'eq', $keyword];
                } elseif (is_mobile($keyword)) { // 手机号
                    $where[] = ['mobile', 'eq', $keyword];
                } elseif (is_numeric($keyword)) { // ID
                    $where[] = ['id', 'eq', $keyword];
                } else { // 用户名、昵称
                    $where[] = ['username|nick|wxmp_openid', 'like', '%' . $keyword . '%'];
                }
            }
            if ($groupId) {
                $where[] = ['group_id', 'eq', $groupId];
            }
            $data = (new UserModel)->getList($where, $page, $limit, ['hasGroup']);
            return $this->success('获取成功', '', $data);
        }

        $_level_select = (new UserGroup)->getSelect();
        $this->assign('_level_select', $_level_select);
        return $this->fetch();
    }

    /**
     * 重置密码
     *
     * @return void
     * @author 617 <email：723875993@qq.com>
     */
    public function resetPwd()
    {
        $id = $this->request->param('id/a');

        $model = new UserModel;

        if (!$model->adminResetPassword($id)) {
            return $this->error('密码重置失败');
        }

        return $this->success('密码重置成功');
    }

    // public function sendMsg()
    // {
    //     if ($this->request->isAjax()) {
    //         $title = $this->request->param('title');
    //         $msg = $this->request->param('msg');
    //         $to_uid = $this->request->param('to_uid');
    //         $data = [
    //             'type' => 0,
    //             'title' => $title,
    //             'msg' => $msg
    //         ];
    //         if ((new Messages)->log($data, $to_uid)) {
    //             return $this->success('发送成功');
    //         }
    //         return $this->error('发送失败');
    //     }
    // }

    public function edit($id = 0)
    {
        $this->assign('groupData', GroupModel::getGroupList());

        if ($this->request->isPost()) {
            // 修改会员分组后 调整会员有效期
            $postData = $this->request->post();
            $group = (new GroupModel)->where('id', $postData['group_id'])->find();

            $model = new UserModel;
            $user = $model->where('id', $postData['id'])->find();

            if ($user['group_id'] != $postData['group_id']) {
                $postData['expire_time'] = $group['expire'];
            }

            if ($postData['expire_time'] == 0) {
                $postData['expire_time'] = $group['expire'];
            }

            if ($model->isUpdate(true)->save($postData) === false) {
                return $this->error($model->getError());
            }
            return $this->success('保存成功', '');
        }
        $formData = (new UserModel)->where('id', $id)->find();
        $this->assign('formData', $formData ? $formData->toArray() : []);
        $template = $this->request->param('template', 'form');
        return $this->fetch($template);
    }

    public function getGroupList()
    {
        $groups = GroupModel::field('id,name')->select();
        return $this->success('获取成功', '', $groups);
    }

    /**
     * 推送模版消息
     *
     * @param integer $id
     * @return void
     * @author 617 <email：723875993@qq.com>
     */
    public function sendTplMsg($id = 0)
    {
        $url = $this->getMsgUrl();

        $config = config('wxmptpl.');
        $tpl_content = explode("\n", $config['tpl_content']);
        $data = [];
        foreach ($tpl_content as $key => $value) {
            if (!empty($value)) {
                $tmp = str_replace('：', ':', $value);
                $tmp = explode(':', $tmp);
                $data[$tmp[0]] = ['value' => (string)$tmp[1]];
            }
        }
        $tpl = [
            "template_id" => $config['template_id'],
            "page" => $config['page'],
            "data" => $data
        ];
        // 单人发送
        $openid = (new UserModel)->where('id', $id)->value('wxmp_openid');
        if (!empty($openid)) {
            $tpl['touser'] = $openid;

            // 检查该用户有无定向订阅
            $sub_info = (new Subscribe)->where(['uid' => $id, 'status' => 0])->find();
            if ($sub_info) {
                // 页面
                if (strstr($config['page'], '/pages/detail/index')) {
                    $tpl['page'] = '/packageA/pages/detail/index?froms=1&id=' . $sub_info['vod_id'];
                }
                // 标题
                if (isset($data['thing1'])) {
                    $tpl['data']['thing1'] = ['value' => $sub_info['vod_title']];
                }
                // 主演
                if (isset($data['thing2'])) {
                    $tpl['data']['thing2'] = ['value' => $sub_info['vod_actor']];
                }
                // 首播时间
                if (isset($data['thing3'])) {
                    $tpl['data']['thing3'] = ['value' => $sub_info['vod_year']];
                }
                // 更新时间
                if (isset($data['time6'])) {
                    $tpl['data']['time6'] = ['value' => date('Y年m月d日 H:i:s', $sub_info['vod_time'])];
                }
                // 评分
                if (isset($data['character_string4'])) {
                    $tpl['data']['character_string4'] = ['value' => $sub_info['vod_score']];
                }
                // 备注
                $remark = config('wxmptpl.tpl_remark');
                if (isset($data['thing5'])) {
                    $tpl['data']['thing5'] = ['value' => $remark];
                }
                (new Subscribe)->where('uid', $id)->setField('status', 1);
            }
            $params = json_encode($tpl, 1);
            $result = Http::post($url, $params);
            $result = json_decode($result, 1);
            if ($result['errcode'] != 0) {
                return $this->error($this->errorCode($result['errcode']) . '；errmsg：' . $result['errmsg']);
            }
            return $this->success('推送成功！');
        }
        return $this->error('未找到该用户');
    }

    public function doSendMsg($page = 1, $limit = 15)
    {
        $url = $this->getMsgUrl();
        $config = config('wxmptpl.');
        $tpl_content = explode("\n", $config['tpl_content']);
        $data = [];
        foreach ($tpl_content as $key => $value) {
            if (!empty($value)) {
                $tmp = str_replace('：', ':', $value);
                $tmp = explode(':', $tmp);
                $data[$tmp[0]] = ['value' => (string)$tmp[1]];
            }
        }
        $tpl = [
            "template_id" => $config['template_id'],
            "page" => $config['page'],
            "data" => $data
        ];
        $map = [];
        $map[] = ['status', '=', 1];
        // 是否开启播放等级限制
        $member_group_switch = config('commoncfg.member_group_switch');
        // 查询所有大于会员控制等级的会员
        $member_group_limit = config('commoncfg.member_group_limit');
        if ($member_group_switch) {
            $map[] = ['group_id', '>=', $member_group_limit];
        }

        $list = (new UserModel)->getList($map, $page, $limit);
        $msg = cache('task_msg');
        if (empty($msg) || $page == 1) {
            $msg = [
                'success' => 0,
                'success_long' => 0,
                'error' => [],
                'error_num' => 0,
                'error_str' => '',
                'error_str_long' => '',
                'count_page' => round(($list['count'] / $limit) + 1),
                'count' => $list['count']
            ];
        }
        if (empty($list['list'])) {
            echo '<p style="font-size: 26px;color: red">';
            echo '全部推送任务执行完毕！共计 ' . $msg['count'] . ' 个！<br/>';
            echo '<font color="green">共推送成功：' . $msg['success_long'] . '个</font><br/>';
            echo '共推送失败：' . $msg['error_num'] . '个<br/>';
            echo '</p>';
            echo '<span style="font-size: 24px;color: red">失败日志记录：</span><br/>';
            echo $msg['error_str_long'];
            die;
        }

        $msg['error'] = [];
        $msg['error_str'] = '';
        $msg['success'] = 0;
        $task = [];
        $error_num = 0;
        foreach ($list['list'] as $key => $value) {
            $tpl['touser'] = $value['wxmp_openid'];
            // 检查该用户有无定向订阅
            $sub_info = (new Subscribe)->where(['uid' => $value['id'], 'status' => 0])->find();
            if ($sub_info) {
                // 页面
                if (strstr($config['page'], '/pages/detail/index')) {
                    $tpl['page'] = '/packageA/pages/detail/index?froms=1&id=' . $sub_info['vod_id'];
                }
                // 标题
                if (isset($data['thing1'])) {
                    $tpl['data']['thing1'] = ['value' => $sub_info['vod_title']];
                }
                // 主演
                if (isset($data['thing2'])) {
                    $tpl['data']['thing2'] = ['value' => $sub_info['vod_actor']];
                }
                // 首播时间
                if (isset($data['thing3'])) {
                    $tpl['data']['thing3'] = ['value' => $sub_info['vod_year']];
                }
                // 更新时间
                if (isset($data['time6'])) {
                    $tpl['data']['time6'] = ['value' => date('Y年m月d日 H:i:s', $sub_info['vod_time'])];
                }
                // 评分
                if (isset($data['character_string4'])) {
                    $tpl['data']['character_string4'] = ['value' => $sub_info['vod_score']];
                }
                // 备注
                $remark = config('wxmptpl.tpl_remark');
                if (isset($data['thing5'])) {
                    $tpl['data']['thing5'] = ['value' => $remark];
                }
                $sub_info->status = 1;
                $sub_info->save();
            }
            $task[] = [
                'url' => $url,
                'params' => $tpl
            ];
            // $ret = Http::post($url, json_encode($tpl, 1));
            // // 单线程请求
            // if ($ret['errcode'] == 0) {
            //     $msg['success_long'] = $msg['success_long'] + 1;
            //     $msg['success'] = $msg['success'] + 1;
            // } else {
            //     $msg['error'][] = [
            //             'code' => $ret['errcode'],
            //             'msg' => $this->errorCode($ret['errcode']) . '；errmsg：' . $ret['errmsg'],
            //             'openid' => $key
            //         ];
            //     $msg['error_num'] = $msg['error_num'] + 1;
            //     $error_num++;
            // }

        }
        $result = async_http($task, true, 'touser');
        foreach ($result as $key => $value) {
            $value = json_decode($value['results'], 1);
            if ($value['errcode'] == 0) {
                $msg['success_long'] = $msg['success_long'] + 1;
                $msg['success'] = $msg['success'] + 1;
            } else {
                $msg['error'][] = [
                    'code' => $value['errcode'],
                    'msg' => $this->errorCode($value['errcode']) . '；errmsg：' . $value['errmsg'],
                    'openid' => $key
                ];
                $msg['error_num'] = $msg['error_num'] + 1;
                $error_num++;
            }
        }
        // $msg['error'] = array_values($msg['error']);
        foreach ($msg['error'] as $key => $value) {
            $msg['error_str_long'] .= '<p>OPENID： ' . $value['openid'] .  '<br/>----错误码：' . $value['code'] . '，错误信息：' . $value['msg'] . "</p>";
            $msg['error_str'] .= '<p>OPENID： ' . $value['openid'] .  '<br/>----错误码：' . $value['code'] . '，错误信息：' . $value['msg'] . "</p>";
        }
        cache('task_msg', $msg);
        // 自动执行
        $page++;

        echo '<p style="font-size: 26px">';
        echo '<font color="green">成功：' . $msg['success'] . '个</font><br/>';
        echo '<font color="red">失败：' . $error_num . '个</font><br/>';
        echo '</p>';
        if ($msg['error_str']) {
            echo '<span style="font-size: 24px;color: red">失败日志：</span><br/>' . $msg['error_str'] . '<br/>';
        }
        echo '共计 <font color="red">' . $msg['count_page'] . '</font> 页，当前正在推送第 <font color="red">' . ($page - 1) . '</font> 页，3秒后跳转到下一页...<br/>';
        $page_url = '/' . config('sys.admin_path') . "/user/index/doSendMsg?page=$page&limit=$limit";
        $html = <<<EOF
<script language="javascript" type="text/javascript">
setTimeout(v => {
    window.location.href="$page_url"
}, 3000);
</script>
EOF;
        echo $html;
        die;
    }

    private function errorCode($code)
    {
        $error = [
            '40001' => 'AppSecret错误或者AppSecret不属于这个小程序，请确认AppSecret的正确性',
            '40003' => 'touser字段openid为空或者不正确',
            '40037' => '订阅模板id为空不正确',
            '43101' => '用户拒绝接受消息，如果用户之前曾经订阅过，则表示用户取消了订阅关系',
            '47003' => '模板参数不准确，可能为空或者不满足规则，errmsg会提示具体是哪个字段出错',
            '41030' => 'page路径不正确，需要保证在现网版本小程序中存在，与app.json保持一致',
        ];
        return $error[$code];
    }

    private function getMsgUrl()
    {
        $ACCESS_TOKEN = cache('access_token');
        if (!$ACCESS_TOKEN) {
            $APPID = config('wechat.appid');
            $APPSECRET = config('wechat.secret');
            //获取access_token
            $access_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$APPID&secret=$APPSECRET";
            $result = Http::get($access_token);
            $result = json_decode($result, true);
            if (isset($result['errcode']) && $result['errcode'] != 0) {
                return $this->error($result['errmsg']);
            }
            if (!isset($result['access_token']) || empty($result['access_token'])) {
                return $this->error('获取access_token失败！');
            }
            cache('access_token', $result['access_token'], 7200);
            $ACCESS_TOKEN = $result["access_token"];
        }
        return 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' . $ACCESS_TOKEN;
    }
}
